package com.mango.iot.gateway.coap.server;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.CoapServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.UnknownHostException;
import java.util.List;

/**
 * Coap Gateway Server
 *
 * @author liangfeihu
 * @since 2021/4/27 下午3:22
 */
@Slf4j
@Service
public class CoapGatewayServer {

    private CoapServer server;

    @Autowired
    private List<CoapResource> resourceList;

    @PostConstruct
    public void init() throws UnknownHostException {
        Integer port = 5683;
        log.info("Starting CoAP transport server at port {}", port);
        this.server = new CoapServer(port);

        // 添加 API Resource
        addResources();

        server.start();
        log.info("CoAP transport Server started!");
    }

    private void addResources() {
        for (CoapResource coapResource : resourceList) {
            server.add(coapResource);
            log.info("[CoapServer] add resource api={}", coapResource.getName());
        }
    }

    @PreDestroy
    public void shutdown() {
        log.info("Stopping CoAP transport!");
        this.server.destroy();
        log.info("CoAP transport stopped!");
    }

}
